<template>
  <el-container style="height: 500px; border: 1px solid #eee">
      <el-main style="overflow: hidden;">
          <div class="search-param" v-if="datatype == 'labmedgroup'">
              <el-input @input="autosearch" @keydown.native="searchkeydown" placeholder="快速检索" prefix-icon="el-icon-search" ref="qcodeinput" style="width:135px;" v-model="qcode"></el-input>
              <el-select v-model="appmethod" placeholder="请选择应用方法" @change="filterdata" clearable style="width:135px; margin-left: 10px;">
                  <el-option v-for="item in $opt.appmethodOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
          </div>
          <!-- <div class="search-param" v-else-if="datatype == 'ipcomputeruser'">
              <el-input @input="autosearch" @keydown.native="searchkeydown" placeholder="快速检索" prefix-icon="el-icon-search" ref="qcodeinput" style="width:135px;" v-model="qcode"></el-input>
              <span style="display: inline-block;margin-left: 10px" v-if="datatype == 'ipcomputeruser'">仪器：</span>
              <rm-ddl-instrument v-model="selitem" v-if="datatype == 'ipcomputeruser'" width="135px" style="display: inline-block;margin-left: 10px" @change="instrchange" ref="ddlinstrument"></rm-ddl-instrument>
          </div> -->
          <div class="search-param" v-else-if="datatype == 'LIS3_req_docno'">
              <el-input  @input="autosearch" @keydown.native="searchkeydown" placeholder="快速检索" prefix-icon="el-icon-search" ref="qcodeinput" style="width:200px;" v-model="qcode"></el-input>
              <span style="display: inline-block;margin-left: 10px" v-if="datatype == 'LIS3_req_docno'">查询方式:</span>
              <el-select v-model="getdoctype" placeholder="请选择过滤条件" :clearable="false" style="width:200px; margin-left: 10px;">
                  <el-option v-for="item in this.getdoctypeoptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
          </div>
          <div class="search-param" v-else>
              <el-input @input="autosearch" @keydown.native="searchkeydown" placeholder="快速检索" prefix-icon="el-icon-search" ref="qcodeinput" style="width:300px;" v-model="qcode" clearable></el-input>
          </div>
          <el-button @click="btnok" icon="el-icon-circle-check" style="margin-left:10px;margin-top:3px;">确定&nbsp;&nbsp;</el-button>
          <el-button @click="btncancel" icon="el-icon-circle-close" style="margin-top:3px;">取消&nbsp;&nbsp;</el-button>
          <el-button style="float:right;margin-top:3px;" @click="refreshdata" icon="el-icon-refresh">刷新数据</el-button>

          <vxe-grid :columns="tableColumn" :pager-config="tablePage" :data="tableData" @cell-dblclick="vxselect" border height="461px" show-header-overflow="tooltip" show-overflow="tooltip" highlight-current-row highlight-hover-row ref="ddlcommonTable" resizable size="mini" stripe style="margin-top:5px"></vxe-grid>
      </el-main>
  </el-container>
</template>
<script>
export default {
  props: { width: { type: String, default: "200px" }, value: [Number, String], datatype: { type: String }, instrid: { type: Number }, appendtobody: { type: Boolean, default: true }, dataname: { type: String }, kindno: { type: String }, rptunitid: { type: Number }, irrelevant: { type: String }, multiple: { type: Boolean, default: false }, param1: { type: String }, stopflag: { type: String, default: "0" }, labgroupid: { type: Number, default: 0 }, purposelabgroupid: { type: Number, default: 0 }, pat_name: { type: String }, pat_no: { type: String}, pat_id: { type: String }, inp_id:{ type: String}, pat_typecode: { type: String }, req_wardno: { type: String }},
  data() {
      return {
          qcode: "",
          appmethod: "", // 药敏组合 测试方法
          selitem: "", //仪器代号
          getdoctype: "3", //获取医生护士不同途径，默认通过接口（1：所有 2：根据当前病人病区 3：通过接口）
          getdoctypeoptions:[{label: "所有" ,value:"1"},{label: "根据病人病区" ,value:"2"},{label: "根据病人信息(接口查询)" ,value:"3"}],
          getdocchangeflag: true, //从接口获取不到医生护士列表的时候，转到所有标志
          fulldata: null,
          tableColumn: [],
          tablePage: {
              pageSize: 1000,
          },
          showirrelevant: "",
          selrow: null,
          tableData: null,
      };
  },
  watch: {
      qcode() {
          this.filterdata();
      },
      getdoctype(){
          this.refreshdata();
      }
  },
  updated() {
      if (this.$refs.qcodeinput) {
          this.$refs.qcodeinput.focus();
      }
      this.showirrelevant = this.irrelevant;
  },
  methods: {
      changeactiverow: function (cindex) {
          var row = this.$refs.ddlcommonTable.getCurrentRow();
          var ridx = this.$refs.ddlcommonTable.getRowIndex(row);
          var newidx = ridx + cindex;
          if (newidx < 0) newidx = 0;
          if (newidx >= this.tableData.length) {
              newidx = 0;
          }
          var newrow = this.tableData[newidx];
          this.$refs.ddlcommonTable.setCurrentRow(newrow);
          // this.$refs.ddlcommonTable.scrollToRow(newrow);
          this.$nextTick(() => {
              if (this.$refs.ddlcommonTable) {
                  var crow = this.$refs.ddlcommonTable.getCurrentRow();
                  this.$refs.ddlcommonTable.scrollToRow(crow);
              }
          });
      },
      searchkeydown: function (evt) {
          if (evt.keyCode == 13) {
              if (this.multiple) {
                  let crow = this.$refs.ddlcommonTable.getCurrentRow();
                  this.$refs.ddlcommonTable.toggleRowSelection(crow);
                  return;
              } else {
                  // console.log("按了回车");
                  this.myvalue = this.$refs.ddlcommonTable.getCurrentRow().hidkey;
                  if (this.myvalue) {
                      this.$emit("change", this.$refs.ddlcommonTable.getCurrentRow().hidkey, this.$refs.ddlcommonTable.getCurrentRow().hidname, this.$refs.ddlcommonTable.getCurrentRow());
                      this.$emit("changeObj", {code:this.$refs.ddlcommonTable.getCurrentRow().hidkey, name:this.$refs.ddlcommonTable.getCurrentRow().hidname, row:this.$refs.ddlcommonTable.getCurrentRow()});
                      // this.clearData();
                  }
              }
          } else if (evt.keyCode == 40) {
              var cindex = 1;
              this.changeactiverow(cindex);
          } else if (evt.keyCode == 38) {
              var cindex = -1;
              this.changeactiverow(cindex);
          }
      },
      autosearch: function (evt) {
          if (evt.keyCode != 13 && evt.keyCode != 40 && evt.keyCode != 38) {
              this.filterdata();
          }
      },
      btnok: function () {
          // this.$emit("change", this.myvalue);
          if (this.multiple) {
              this.$emit("change", this.$refs.ddlcommonTable.getSelectRecords());
              this.$emit("changeObj", {code:'', name:'', row:this.$refs.ddlcommonTable.getSelectRecords()});
          } else {
              this.myvalue = this.$refs.ddlcommonTable.getCurrentRow().hidkey;
              this.$emit("change", this.$refs.ddlcommonTable.getCurrentRow().hidkey, this.$refs.ddlcommonTable.getCurrentRow().hidname, this.$refs.ddlcommonTable.getCurrentRow());
              this.$emit("changeObj", {code:this.$refs.ddlcommonTable.getCurrentRow().hidkey, name:this.$refs.ddlcommonTable.getCurrentRow().hidname, row:this.$refs.ddlcommonTable.getCurrentRow()});
          }
          // this.clearData();
          // this.$emit("returnBack", this.myvalue);
      },
      btncancel: function () {
          this.$emit("cancel");
      },
      setcol() {
          var collist = [];
          if (this.multiple) {
              collist.push({ type: "selection", width: 50, align: "center" });
          }
          for (let i = 0, len = this.fulldata.Cols.length; i < len; i++) {
              const item = this.fulldata.Cols[i];
              if (item.field != "hidkey" && item.field != "hidname" && item.field != "inputcode" && item.field != "shortmsgcode" && item.field != "hidtelcode") {
                  let colitem = {
                      field: item.field,
                      title: item.title,
                      width: item.width,
                  };
                  collist.push(colitem);
              }
          }
          this.tableColumn = collist;
          // console.log(collist);
      },

      filterdata() {
          let cData = this.fulldata.Data;
          try {
              if (this.qcode != "") {
                  cData = cData.filter((item) => (!!item.hidkey ? item.hidkey.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false) || (!!item.hidname ? item.hidname.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false) || (!!item.inputcode ? item.inputcode.toUpperCase().indexOf(this.qcode.toUpperCase()) > -1 : false));
              }
              if (this.datatype == "labmedgroup" && this.appmethod) {
                  cData = cData.filter((item) => item["应用方法"] && this.appmethod.toUpperCase().indexOf(item["应用方法"].toUpperCase()) > -1);
              }
              if ((this.datatype == "labmed" || this.datatype == "med") && this.stopflag == "1") {
                  cData = cData.filter((item) => item.stopflag != this.stopflag);
              }
              if (this.datatype == "labgroup" && this.labgroupid > 0) {
                  cData = cData.filter((item) => item.hidkey == this.labgroupid);
              }
              if (this.datatype == "bactpurpose" && this.labgroupid > 0) {
                  cData = cData.filter((item) => item["检验工作组ID"] == this.labgroupid);
              }

              if (cData.length > 0) {
                  this.selrow = cData[0];
              } else {
                  this.selrow = {};
              }
              // console.log(this.irrelevant);
              let haveall = cData.find((m) => m.hidkey == "All" || m.hidkey == "-1");
              if (this.irrelevant == "deptShowIrrelevant") {
                  //科室显示无关
                  let dept = { 科室名称: "无关", 科室代码: "All", 科室类别: "", hidkey: "All", hidname: "无关", HIS代码: "", inputcode: "WG" };
                  if (!haveall) cData.splice(0, 0, dept);
              } else if (this.irrelevant == "specimenShowIrrelevant") {
                  //标本类型显示无关
                  let specimen = { specimen_name: "无关", specimen_code: "All", specimentype: "", hidkey: "All", hidname: "无关", inputcode: "WG", seq: 0 };
                  if (!haveall) cData.splice(0, 0, specimen);
              } else if (this.irrelevant == "physicycleShowIrrelevant") {
                  //生理周期显示无关
                  let physicycle = { 名称: "无关", 代号: "All", hidkey: "All", hidname: "无关", inputcode: "WG" };
                  if (!haveall) cData.splice(0, 0, physicycle);
              } else if (this.irrelevant == "diagicdShowIrrelevant") {
                  //诊断IDD显示无关
                  let diagicd = { 诊断名称: "无关", ICD10编码: "All", 诊断代码: "All", hidkey: "All", hidname: "无关", inputcode: "WG" };
                  if (!haveall) cData.splice(0, 0, diagicd);
              } else if (this.irrelevant == "pattypeShowIrrelevant") {
                  //病人类型显示无关
                  let seccode = { 名称: "无关", 代号: "All", 助记符: "All", hidkey: "All", hidname: "无关", inputcode: "WG" };
                  if (!haveall) cData.splice(0, 0, seccode);
              } else if (this.irrelevant == "reqgroupnoShowIrrelevant") {
                  //分单类别显示无关
                  let reqgroup = { req_groupcode: "-1", req_groupna: "无关", req_groupname: "无关", hidkey: "-1", hidname: "无关", inputcode: "WG" };
                  if (!haveall) cData.splice(0, 0, reqgroup);
              } else if (this.irrelevant == "groupShowIrrelevant") {
                  //检验工作组显示无关
                  let progroup = { 检验工作组名称: "无关", 检验工作组代码: "All", 所属检验科室代码: "", 所属检验科室: "", 拼音码: "", 检验工作组ID: "", hidkey: "-1", hidname: "无关", inputcode: "WG", seq: 0 };
                  if (!haveall) cData.splice(0, 0, progroup);
              }

              this.tableData = cData;
              this.$nextTick(() => {
                  if (this.$refs.ddlcommonTable) {
                      if (this.selrow) {
                          this.$refs.ddlcommonTable.setCurrentRow(this.selrow);
                      }
                  }
              });
          } catch (e) {
              console.log("erro", e);
          }
      },
      refreshdata() {
          // localStorage.removeItem("RMCOMDDL_" + this.datatype + "_" + this.kindno + "_" + this.instrid);
          let key = "RMCOMDDL_POP_" + (this.datatype ? this.datatype : "") + "_" + (this.kindno ? this.kindno : "") + "_" + (this.instrid ? this.instrid : "") + "_" + (this.rptunitid ? this.rptunitid : "") + "_" + (this.param1 ? this.param1 : "")+ "_" + (this.req_wardno ? this.req_wardno : "") + "_" + (this.pat_no ? this.pat_no : "") + "_" + (this.getdoctype ? this.getdoctype : "");
          let comdata = this.$ddldata.common_data;

          let dlldataitem = comdata.find((t) => t.key == key);
          if (dlldataitem) {
              comdata.splice(comdata.indexOf(dlldataitem), 1);
              this.$ddldata.common_data = comdata;
          }
          this.loadAllData();
      },
      loadAllData: function () {
          // let ccdata = JSON.parse(localStorage.getItem("RMCOMDDL_" + this.datatype + "_" + this.kindno + "_" + this.instrid + "_" + this.rptunitid));

          let key = "RMCOMDDL_POP_" + (this.datatype ? this.datatype : "") + "_" + (this.kindno ? this.kindno : "") + "_" + (this.instrid ? this.instrid : "") + "_" + (this.rptunitid ? this.rptunitid : "") + "_" + (this.param1 ? this.param1 : "")+ "_" + (this.req_wardno ? this.req_wardno : "") + "_" + (this.pat_no ? this.pat_no : "") + "_" + (this.getdoctype ? this.getdoctype : "");
          let ccdata = null;
          let comdata = this.$ddldata.common_data;
          if (comdata) {
              let dlldataitem = comdata.find((t) => t.key == key);
              if (dlldataitem && dlldataitem.val) {
                  ccdata = dlldataitem.val;
              } else {
                  ccdata = null;
              }
          }
          //console.log("ccdata", ccdata);
          if (!ccdata) {
              this.$tool
                  .request({
                      url: "ucent/ddl",
                      method: "post",
                      data: {
                          action: this.datatype,
                          kindno: this.kindno,
                          instrid: this.instrid,
                          rptunitid: this.rptunitid,
                          param1: this.param1,
                          stopflag: this.stopflag,
                          selitem: this.selitem,
                          req_wardno: this.req_wardno,
                          pat_name: this.pat_name,
                          pat_no: this.pat_no,
                          pat_id: this.pat_id,
                          inp_id: this.inp_id,
                          pat_typecode: this.pat_typecode,
                          getdoctype: this.getdoctype,
                      },
                  })
                  .then((res) => {
                      //console.log("commonres", res);
                      this.fulldata = res;
                      this.setcol();
                      this.filterdata();
                      try {
                          // localStorage.setItem("RMCOMDDL_" + this.datatype + "_" + this.kindno + "_" + this.instrid, JSON.stringify(res));
                          this.$ddldata.common_data.push({ key: key, val: res });
                      } catch (e) {}
                      //当接口查不出通知人列表的时候，需要去查询所有
                      if(this.fulldata.Data.length == 0 && this.getdoctype == "3" && this.datatype == "LIS3_req_docno" && this.getdocchangeflag){
                          this.getdoctype = "1";
                          this.getdocchangeflag = false;
                      }
                  })
                  .catch((e) => {
                      this.myvalue = e;
                      //console.log("erro", e);
                  });
          } else {
              this.fulldata = ccdata;
              this.setcol();
              this.filterdata();
              if(this.fulldata.Data.length == 0 && this.getdoctype == "3" && this.datatype == "LIS3_req_docno" && this.getdocchangeflag){
                  this.getdoctype = "1";
                  this.getdocchangeflag = false;
              }
          }
      },
      vxselect: function (data, evt) {
          if (this.multiple) {
              return;
          }
          this.myvalue = data.row.hidkey;
          this.$emit("change", data.row.hidkey, data.row.hidname, data.row);
          this.$emit("changeObj", {code:data.row.hidkey, name:data.row.hidname, row:data.row});
          // this.clearData();
      },
      instrchange(val) {
          this.$refs.ddlinstrument.$refs.ddlrptunitSelect.blur();
          this.selitem = val;
          this.refreshdata();
      },
      // clearData() {
      //     this.qcode = '';
      //     this.tableData = XEUtils.clone(this.fulldata.Data, true);
      // },
  },
  mounted() {
      if (this.datatype == "ipcomputeruser") {
          this.refreshdata();
      } else {
          this.loadAllData();
      }
      if (this.$refs.qcodeinput) {
          this.$refs.qcodeinput.focus();
      }
  },
};
</script>
<style scoped>
.el-main {
  padding: 0;
}

/deep/.el-dialog__body {
  padding-top: 0px;
  padding-bottom: 0px;
}
.search-param {
  display: inline-block;
}
</style>
